package cn.flying.cloud.task.core.context;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import cn.flying.cloud.task.core.annotation.JobHandler;
import cn.flying.cloud.task.core.handler.AbstractJobHandler;

/**
 * @author: admin
 * @date: 2025年03月12日 23:55
 * @version: 1.0
 */
@Component
public class JobHandlerCache implements ApplicationListener<ContextRefreshedEvent> {

    private final Map<String, AbstractJobHandler> jobHandlerCache = new ConcurrentHashMap<>();

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 获取 Spring 容器
        Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(JobHandler.class);
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            Object bean = entry.getValue();
            // 获取 Bean 上的 JobHandler 注解
            JobHandler handler = bean.getClass().getAnnotation(JobHandler.class);
            if (handler != null) {
                String name = handler.name();
                // 将 Bean 缓存到 Map 中
                jobHandlerCache.put(name, (AbstractJobHandler) bean);
            }
        }
    }

    public Map<String, AbstractJobHandler> getJobHandlerCache() {
        return jobHandlerCache;
    }
}